package com.wanyangproject.shouye;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.adapter.XuanZeYuanQuAdapter;
import com.wanyangproject.entity.HuoQuYuanQuLieBiaoEntity;
import com.wanyangproject.entity.SheZhiYuanQuEntity;
import com.wanyangproject.entity.SheZhiYuanQuNameEntity;
import com.wanyangproject.entity.SheZhiYuanQuNameIIdEntity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.SharedPreferencesXuanZeYuanQu;
import com.wanyangproject.widget.suspensionindexbar.IndexBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class XuanZeYuanQuActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_wancheng)
    TextView tvWancheng;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_dangqian)
    TextView tvDangqian;
    public XuanZeYuanQuAdapter xuanZeYuanQuAdapter;
    @BindView(R.id.zimu)
    IndexBar zimu;
    private HuoQuYuanQuLieBiaoEntity huoQuYuanQuLieBiaoEntity;
    private String yuanqu;
    private int pos = -1;
    private ArrayList<String> suoyin = new ArrayList<>();// 索引A-Z
    private ArrayList<JSONObject> jsonArrayFenZu = new ArrayList<>();// 分组的数据
    private JSONObject jsonObject1;
    private LinearLayoutManager manager;
    private String xuanze;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuan_ze_yuan_qu);
        ButterKnife.bind(this);


        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }



        if(ContractUtils.getYuanquname(XuanZeYuanQuActivity.this) != null){
            tvDangqian.setText("当前："+ContractUtils.getYuanquname(XuanZeYuanQuActivity.this));
        }




//        园区列表的网络请求
        initYuanQuLieBiaoHttp();



        Intent intent = getIntent();
        xuanze = intent.getStringExtra("xuanze");


        zimu.setmOnIndexPressedListener(new IndexBar.onIndexPressedListener() {
            @Override
            public void onIndexPressed(int index, String text) {
//                System.out.println(index + "    index");
//                System.out.println(text + "     text");
//                Intent intent0 = new Intent(XuanZeYuanQuActivity.this, YuanQuQiYeActivity.class);
//                intent0.putExtra("title", text);// 点击单个字母传的标题
//                startActivity(intent0);



                int pos = 0;
                if (suoyin.contains(text)) {
                    int a = suoyin.indexOf(text);
                    int sum = 0;// 之和
                    for (int i = 0; i < a; i++) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = jsonObject1.getJSONArray(suoyin.get(i));
                            sum += jsonArray.length();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    pos = sum;
                    System.out.println(pos + "    pos");
                    recyclerView.setLayoutManager(manager);
                    manager.scrollToPosition(pos); // 自动滚动到哪一行
                }
            }

            @Override
            public void onMotionEventEnd() {
                System.out.println("111111111111");
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
//        SharedPreferences sharedPreferences = getSharedPreferences("yuanqu", Context.MODE_PRIVATE);
//        yuanqu = sharedPreferences.getString("yuanqu", "");
//        if (yuanqu.equals("")) {
//
//        } else {
//            tvDangqian.setText("当前：" + yuanqu);
//            System.out.println(yuanqu + "    当前的园区名");
//        }
    }


    //    园区列表的网络请求
    private void initYuanQuLieBiaoHttp() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "park/getParkByName")
                .addHeader("token", ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressDialog.dismiss();
                        System.out.println(response + "    获取园区列表的网络请求");
                        ContractUtils.Code500(XuanZeYuanQuActivity.this, response);
                        int aa = jsonArrayFenZu.size();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            jsonObject1 = jsonObject.getJSONObject("response");
                            Iterator<String> keys = jsonObject1.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                JSONArray jsonArray = jsonObject1.getJSONArray(key);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jj = (JSONObject) jsonArray.get(i);
                                    jsonArrayFenZu.add(jj);
                                }

                                int bb = jsonArrayFenZu.size();
                                if (aa == bb) {
                                    Toast.makeText(XuanZeYuanQuActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
                                if (suoyin.contains(key)) {

                                } else {
                                    suoyin.add(key);
                                }
//                                suoyin.add(key);

//                                String value = jsonObject.getString(key);
//                                Log.e("TAG", "key=" + key + "\tvalue=" + value);//键值对key value
                                System.out.println(key + "    keykey");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


//                        Gson gson = new Gson();
//                        huoQuYuanQuLieBiaoEntity = gson.fromJson(response, HuoQuYuanQuLieBiaoEntity.class);
//
                        xuanZeYuanQuAdapter = new XuanZeYuanQuAdapter(XuanZeYuanQuActivity.this, jsonArrayFenZu);
                        manager = new LinearLayoutManager(XuanZeYuanQuActivity.this);
                        recyclerView.setLayoutManager(manager);
                        recyclerView.setAdapter(xuanZeYuanQuAdapter);


                        //                            索引

//                            manager.smoothScrollToPosition(this,,pos);

//                        xuanZeYuanQuAdapter.setXuanZeYuanQuClick(new XuanZeYuanQuAdapter.XuanZeYuanQuClick() {
//                            @Override
//                            public void xuanzeyuanquClick(int position) {

//                                pos = position;
//                                SharedPreferencesXuanZeYuanQu.saveYuanQu(MyApp.getContext(),huoQuYuanQuLieBiaoEntity.getMsg().get(position).getParkName());
//
//                                System.out.println(huoQuYuanQuLieBiaoEntity.getMsg().get(position).getParkName()+"    保存园区名字");
//
//                                SharedPreferences sharedPreferences = getSharedPreferences("yuanqu", Context.MODE_PRIVATE);
//                                yuanqu = sharedPreferences.getString("yuanqu", "");
//                                if(yuanqu.equals("")){
//
//                                }else{
//                                    tvDangqian.setText("当前："+yuanqu);
//                                    System.out.println(yuanqu+"    当前的园区名");
//                                }

//                            }
//                        });
                    }
                });
    }


    @OnClick({R.id.image_back, R.id.tv_wancheng, R.id.recyclerView, R.id.tv_dangqian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.tv_wancheng:

//              设置常用园区的网络请求
                initSheZhiChangYongYuanQuHttp();

                //        设置园区接口
                initSheZhiYuanQuHttp();

//                if(pos == -1){
//                    finish();
//                }else{
////                    获取园区id发送广播
//                    Intent intent = new Intent();
//                    intent.putExtra("parkId",huoQuYuanQuLieBiaoEntity.getMsg().get(pos).getParkId()+"");
//                    intent.setAction("yuanquid");
//                    sendBroadcast(intent);
//                    System.out.println(huoQuYuanQuLieBiaoEntity.getMsg().get(pos).getParkId() +"   发送的园区id");
//                    finish();
//                }
                break;
            case R.id.recyclerView:
                break;
            case R.id.tv_dangqian:
                break;
        }
    }



    //    设置园区接口
    private void initSheZhiYuanQuHttp() {
        String s = "";
        ArrayList<JSONObject> list = xuanZeYuanQuAdapter.list;
        for (int i = 0; i < list.size(); i++) {
            JSONObject msgBean = list.get(i);
            try {
                s = s + msgBean.getString("parkId");
                if (i != list.size() - 1) {
                    s = s + ",";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



        System.out.println(s + "           ssssssssssss");


        if(xuanze != null) {
            if (xuanze.equals("1")) {
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL + "user/setDefaultPark")
                        .addHeader("token", ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
                        .addParams("parkId", s)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response + "               设置园区接口");
                                if (response.indexOf("200") != -1) {
                                    Gson gson = new Gson();
                                    SheZhiYuanQuNameIIdEntity sheZhiYuanQuNameIIdEntity = gson.fromJson(response, SheZhiYuanQuNameIIdEntity.class);
                                    SharedPreferencesXuanZeYuanQu.saveYuanQu(XuanZeYuanQuActivity.this,sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkId(),
                                            sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkName());

                                    ContractUtils.setParkId(sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkId());
                                    ContractUtils.setPhone(sheZhiYuanQuNameIIdEntity.getResponse().getUsername());
                                    ContractUtils.setYuanquname(sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkName());
                                    ContractUtils.setTypeId(sheZhiYuanQuNameIIdEntity.getResponse().getTypeId());
                                    ContractUtils.setTypeId22(sheZhiYuanQuNameIIdEntity.getResponse().getTypeId2());
                                    finish();
                                }
                            }
                        });
            }else if(xuanze.equals("2")){
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL + "user/setDefaultPark")
                        .addHeader("token", ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
                        .addParams("parkId", s)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response + "               设置园区接口");
                                if (response.indexOf("200") != -1) {
                                    Gson gson = new Gson();
                                    SheZhiYuanQuNameIIdEntity sheZhiYuanQuNameIIdEntity = gson.fromJson(response, SheZhiYuanQuNameIIdEntity.class);
                                    SharedPreferencesXuanZeYuanQu.saveYuanQu(XuanZeYuanQuActivity.this,sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkId(),
                                            sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkName());
                                    ContractUtils.setParkId(sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkId());
                                    ContractUtils.setPhone(sheZhiYuanQuNameIIdEntity.getResponse().getUsername());
                                    ContractUtils.setYuanquname(sheZhiYuanQuNameIIdEntity.getResponse().getParkInfo().getParkName());
                                    ContractUtils.setTypeId(sheZhiYuanQuNameIIdEntity.getResponse().getTypeId());
                                    ContractUtils.setTypeId22(sheZhiYuanQuNameIIdEntity.getResponse().getTypeId2());
                                    finish();
                                }
                            }
                        });
            }
        }
    }





    //    设置常用园区的网络请求
    private void initSheZhiChangYongYuanQuHttp() {
        String s = "";
        ArrayList<JSONObject> list = xuanZeYuanQuAdapter.list;
        for (int i = 0; i < list.size(); i++) {
            JSONObject msgBean = list.get(i);
            try {
                s = s + msgBean.getString("parkId");
                if (i != list.size() - 1) {
                    s = s + ",";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



        System.out.println(s + "           ssssssssssss");

        if(xuanze != null){
            if(xuanze.equals("1")){
                //    之前
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL + "park/setUserPark")
                        .addHeader("token", ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
                        .addParams("parkId", s)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e + "         设置常用园区eeeeeeeee");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response + "         设置常用园区的网络请求");
                                if (response.indexOf("200") != -1) {
                                    Gson gson = new Gson();
                                    SheZhiYuanQuEntity sheZhiYuanQuEntity = gson.fromJson(response, SheZhiYuanQuEntity.class);
                                    Toast.makeText(XuanZeYuanQuActivity.this, sheZhiYuanQuEntity.getMsg(), Toast.LENGTH_SHORT).show();
                                    finish();
                                }else if(response.indexOf("400") != -1){
                                    ContractUtils.Code400(XuanZeYuanQuActivity.this,response);
                                }
                            }
                        });
            }else if(xuanze.equals("2")){
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL+"user/setDefaultPark")
                        .addHeader("token",ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
                        .addParams("parkId",s)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response+"               设置园区接口");
                                if(response.indexOf("200") != -1){
                                    Gson gson = new Gson();
                                    SheZhiYuanQuNameEntity sheZhiYuanQuNameEntity = gson.fromJson(response, SheZhiYuanQuNameEntity.class);
                                    SharedPreferencesXuanZeYuanQu.saveYuanQu(XuanZeYuanQuActivity.this,sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkId(),sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkName());
                                    ContractUtils.setParkId(sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkId());
                                    ContractUtils.setPhone(sheZhiYuanQuNameEntity.getResponse().getUsername());
                                    ContractUtils.setYuanquname(sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkName());
                                    ContractUtils.setTypeId(sheZhiYuanQuNameEntity.getResponse().getTypeId());
                                    ContractUtils.setTypeId22(sheZhiYuanQuNameEntity.getResponse().getTypeId2());
                                    finish();
                                }else if(response.indexOf("400") != -1){
                                    ContractUtils.Code400(XuanZeYuanQuActivity.this,response);
                                }
                            }
                        });
            }
        }





//        之后
//        OkHttpUtils.post()
//                .url(ContractUtils.LOGIN_URL+"user/setDefaultPark")
//                .addHeader("token",ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
//                .addParams("parkId",s)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        System.out.println(response+"               设置园区接口");
//                        if(response.indexOf("200") != -1){
//                            Gson gson = new Gson();
//                            SheZhiYuanQuNameEntity sheZhiYuanQuNameEntity = gson.fromJson(response, SheZhiYuanQuNameEntity.class);
//                            SharedPreferencesXuanZeYuanQu.saveYuanQu(XuanZeYuanQuActivity.this,sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkId(),sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkName());
//                            ContractUtils.setParkId(sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkId());
//                            ContractUtils.setPhone(sheZhiYuanQuNameEntity.getResponse().getUsername());
//                            ContractUtils.setYuanquname(sheZhiYuanQuNameEntity.getResponse().getParkInfo().getParkName());
//                            ContractUtils.setTypeId(sheZhiYuanQuNameEntity.getResponse().getTypeId());
//                            ContractUtils.setTypeId22(sheZhiYuanQuNameEntity.getResponse().getTypeId2());
//                            finish();
//                        }
//                    }
//                });









////        之前
//        OkHttpUtils.post()
//                .url(ContractUtils.LOGIN_URL + "park/setUserPark")
//                .addHeader("token", ContractUtils.getTOKEN(XuanZeYuanQuActivity.this))
//                .addParams("parkId", s)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        System.out.println(e + "         设置常用园区eeeeeeeee");
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        System.out.println(response + "         设置常用园区的网络请求");
//                        if (response.indexOf("200") != -1) {
//                            Gson gson = new Gson();
//                            SheZhiYuanQuEntity sheZhiYuanQuEntity = gson.fromJson(response, SheZhiYuanQuEntity.class);
//                            Toast.makeText(XuanZeYuanQuActivity.this, sheZhiYuanQuEntity.getMsg(), Toast.LENGTH_SHORT).show();
//                            finish();
//                        }
//                    }
//                });
    }
}
